import { arrayMethods } from "./arrayProto"
import defineReactive from "./defineReactive"
import { def, observe } from "../common";

function protoAugment(target, src, keys) {
    target.__proto__ = src
}
function copyAgument (target, src, keys) {
    for(let key of keys) {
        def(target, key, src[key])
    }
}
/* 
 一、监听的数组重写方法
 二、在Observer上保存dep，因为上述原因
 */
 const hasProto = '__proto__' in {}
 const arrayKeys = Object.getOwnPropertyNames(arrayMethods)
export default class Observer {
    constructor (value) {
        this.value = value
        this.dep = new Dep()
        def(value, '__ob__', this)
        if (Array.isArray(value)){
            // 监听数组元素
            this.observeArray(value)
            const augment = hasProto ? protoAugment : copyAgument
            // 设置array原型 --- arrayMethods 监听数组方法
            augment(value, arrayMethods, arrayKeys)
        } else {
            this.walk(value)
        }
    }
    // 只有在value是obj的情况下使用
    walk (obj) {
        for(let key of Object.keys(obj)){
            defineReactive(obj, key, obj[key])
        }
    }
    observeArray(items) {
        for(let item of items){
            observe(item)
        }
    }
}